package com.emm.yixun.website.controller.estate;
//框架包
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.emm.yixun.anotations.MerchantResourcesConfig;
import com.emm.yixun.common.model.BaseCodeType;
import com.emm.yixun.common.model.BaseCodeValue;
import com.emm.yixun.common.model.Department;
import com.emm.yixun.common.model.IndustDataVersion;
import com.emm.yixun.common.model.LevelStaticSalesData;
import com.emm.yixun.common.model.LevelStaticSalesDataChild;
import com.emm.yixun.common.model.Project;
import com.emm.yixun.common.model.ProjectPremises;
import com.emm.yixun.common.model.ProjectPremisesIndustData;
import com.emm.yixun.common.model.ProjectPremisesInfo;
import com.emm.yixun.common.model.ProjectPremisesPmo;
import com.emm.yixun.common.model.StaticSalesData;
import com.emm.yixun.common.model.StaticSalesIndustData;
import com.emm.yixun.common.model.User;
import com.emm.yixun.common.model.dto.BaseCodeTypeDto;
import com.emm.yixun.common.model.dto.BaseCodeValueDto;
import com.emm.yixun.common.model.dto.DepartmentDto;
import com.emm.yixun.common.model.dto.ProjectPremisesDto;
import com.emm.yixun.common.model.dto.ProjectPremisesIndustDataDto;
import com.emm.yixun.common.model.dto.ProjectPremisesInfoDto;
import com.emm.yixun.common.model.dto.ProjectPremisesPmoDto;
import com.emm.yixun.common.model.dto.RootClass;
import com.emm.yixun.common.model.dto.SaleReturnPmoDto;
import com.emm.yixun.common.model.dto.ViewVersion;
import com.emm.yixun.common.model.enums.CodeTypeEnum;
import com.emm.yixun.common.model.enums.DelFlagEnum;
import com.emm.yixun.common.model.enums.DeliveryStatusEnum;
import com.emm.yixun.common.model.enums.ObjectTypeEnum;
import com.emm.yixun.common.model.enums.ProjectTypeEnum;
import com.emm.yixun.common.model.enums.RenovationTypeEnums;
import com.emm.yixun.common.model.enums.SaleReturnEnum;
import com.emm.yixun.common.model.enums.SalesStatusEnum;
import com.emm.yixun.common.model.enums.TenementTypeEnum;
import com.emm.yixun.common.model.pmo.DynamiSalesData;
import com.emm.yixun.common.model.pmo.DynamiSalesIndustData;
import com.emm.yixun.common.model.pmo.LevelDynamiSalesData;
import com.emm.yixun.common.page.Page;
import com.emm.yixun.common.page.PageUtil;
import com.emm.yixun.common.response.Response;
import com.emm.yixun.common.response.ResponseList;
import com.emm.yixun.estate.service.ProjectPremisesInfoServiceFacade;
import com.emm.yixun.estate.service.ProjectPremisesPmoServiceFacade;
import com.emm.yixun.estate.service.ProjectPremisesServiceFacade;
import com.emm.yixun.estate.service.ProjectServiceFacade;
import com.emm.yixun.estate.service.SaleReturnPmoServiceFacade;
import com.emm.yixun.system.service.BaseCodeTypeServiceFacade;
import com.emm.yixun.system.service.BaseCodeValueServiceFacade;
import com.emm.yixun.system.service.DepartmentServiceFacade;
import com.emm.yixun.website.common.ajax.AjaxRes;
import com.emm.yixun.website.common.utils.base.Const;
import com.emm.yixun.website.common.utils.security.ShiroUtil;
import com.emm.yixun.website.controller.base.BaseController;
import com.emm.yixun.website.service.estate.ProjectPremisesIndustDataService;
import com.emm.yixun.website.vo.estate.ProjectPremisesInfoVo;
import com.emm.yixun.website.vo.estate.ProjectPremisesVo;
import com.emm.yixun.website.vo.estate.SaleReturnPmoVo;
//变化的引用
//common
//website
import com.opensymphony.oscache.util.StringUtil;

@Controller
@RequestMapping("/estate/projectPremises/")
public class ProjectPremisesController extends BaseController<ProjectPremises> {

	@Autowired
	private ProjectPremisesServiceFacade projectPremisesServiceFacade;
	@Autowired
	private ProjectServiceFacade projectServiceFacade;
	@Autowired
	private DepartmentServiceFacade departmentServiceFacade;
	@Autowired
	private ProjectPremisesInfoServiceFacade projectPremisesInfoServiceFacade;
	@Autowired
	private ProjectPremisesPmoServiceFacade projectPremisesPmoServiceFacade;
	@Autowired
	private ProjectPremisesIndustDataService projectPremisesIndustDataService;
	@Autowired
	private SaleReturnPmoServiceFacade saleReturnPmoServiceFacade;
	@Autowired
	private BaseCodeValueServiceFacade baseCodeValueServiceFacade; 
	@Autowired
	private BaseCodeTypeServiceFacade baseCodeTypeServiceFacade;
	
	@RequestMapping(value = "index")
	public String index(ModelMap map) {
		if (doSecurityIntercept(Const.RESOURCES_TYPE_MENU)) {
			// 查询菜单按钮权限
			map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
			return "/estate/projectPremises/list";
		}
		return Const.NO_AUTHORIZED_URL;
	}

	public List<BaseCodeValue> getBaseCodeValue(){
		List<BaseCodeValue> array = new ArrayList<BaseCodeValue>();
		BaseCodeTypeDto baseCode = new BaseCodeTypeDto();
		baseCode.setCodeType(CodeTypeEnum.CUSTOMER_02.getNo());
		ResponseList<BaseCodeType> responseList = baseCodeTypeServiceFacade.findByDto(baseCode);
		if(responseList.isSuccess()&&responseList.getEntity()!=null&&responseList.getEntity().size()>0){
			for (BaseCodeType codeType:responseList.getEntity()) {
				BaseCodeValueDto baseValue = new BaseCodeValueDto();
				baseValue.setTypeId(codeType.getId());
				ResponseList<BaseCodeValue> baseCodeList = baseCodeValueServiceFacade.findByDto(baseValue);
				if(baseCodeList.isSuccess()&&baseCodeList.getEntity()!=null&&baseCodeList.getEntity().size()>0){
					array.addAll(baseCodeList.getEntity());
				}
			}
		}
		return array;
	}
	
	@RequestMapping(value = "save_edit_lc")
	public String basicSaveEdit(ModelMap map, Long id) {
		// 产品类型
		map.put("projectTypes", ProjectTypeEnum.values());
		// 交付情况
		map.put("deliveryStatusEnums", DeliveryStatusEnum.values());
		// 销售情况
		map.put("salesStatusEnums", SalesStatusEnum.values());

		// 物业类型
		map.put("tenementTypeEnums", TenementTypeEnum.values());
		// 装修标准
		map.put("renovationTypeEnums", RenovationTypeEnums.values());


		// 业态数据
		ProjectPremisesIndustDataDto dataDto = new ProjectPremisesIndustDataDto();
		dataDto.setPremisesId(id);
		List<ProjectPremisesIndustData> datas = projectPremisesIndustDataService.findListByDto(dataDto);
		
		if (datas == null){
			datas = new ArrayList<ProjectPremisesIndustData>();
			map.put("industTime", new JSONArray().toJSONString());
		}else{
			IndustDataVersion inds = datas.get(0).getIndustDataVersion();
			List<String> array = new ArrayList<String>();
			array.add(inds.getValue1());
			array.add(inds.getValue3());
			array.add(inds.getValue5());
			array.add(inds.getValue7());
			array.add(inds.getValue9());
			array.add(inds.getValue11());
			map.put("industTime", JSON.toJSON(array));
		}
			
		map.put("industDatas", JSON.toJSON(datas));
		
		
		map.put("industMarkEnums", JSON.toJSON(getBaseCodeValue()));
		User user = ShiroUtil.getCurrentUser();
		DepartmentDto dto = new DepartmentDto();
		dto.setMerchantId(user.getMerchantId());
		ResponseList<Department> responseList = departmentServiceFacade.findByDto(dto);
		if (responseList.isSuccess() && null != responseList.getEntity()) {
			map.put("departments", responseList.getEntity());
		} else {
			map.put("departments", new ArrayList<Department>());
		}

		Response<ProjectPremises> response = projectPremisesServiceFacade.findById(id);
		if (response.isSuccess() && response.getEntity() != null) {
			// 项目信息
			Response<Project> resProject = projectServiceFacade.findById(response.getEntity().getProjectId());
			if (resProject.isSuccess() && resProject.getEntity() != null) {
				map.put("project", resProject.getEntity());
			}

			// 组团信息
			map.put("premises", response.getEntity());

			// 组团详情
			ProjectPremisesInfoDto ppiDto = new ProjectPremisesInfoDto();
			ppiDto.setPremisesId(id);
			ResponseList<ProjectPremisesInfo> resPPI = projectPremisesInfoServiceFacade.findByDto(ppiDto);
			if (resPPI.isSuccess() && null != resPPI.getEntity() && resPPI.getEntity().size() > 0) {
				map.put("projectPremisesInfo", resPPI.getEntity().get(0));
			}

			ProjectPremisesPmoDto pppDto = new ProjectPremisesPmoDto();
			pppDto.setPremisesId(id);
			ResponseList<ProjectPremisesPmo> resPPP = projectPremisesPmoServiceFacade.findByDto(pppDto);
			if (resPPP.isSuccess() && null != resPPP.getEntity() && resPPP.getEntity().size() > 0) {
				ProjectPremisesPmo ppp = resPPP.getEntity().get(0);
				if (StringUtils.isNotEmpty(ppp.getLogoUrl())) {
					String logoList[] = ppp.getLogoUrl().split("[,]");
					map.put("logoList", logoList);
				}
				if (StringUtils.isNotEmpty(ppp.getTraffiDiagra())) {
					String traffiDiagraList[] = ppp.getTraffiDiagra().split("[,]");
					map.put("traffiDiagraList", traffiDiagraList);
				}
				if (StringUtils.isNotEmpty(ppp.getAroundSupporDiagra())) {
					String aroundSupporDiagraList[] = ppp.getAroundSupporDiagra().split("[,]");
					map.put("aroundSupporDiagraList", aroundSupporDiagraList);
				}
				if (StringUtils.isNotEmpty(ppp.getMasterDiagra())) {
					String masterDiagraList[] = ppp.getMasterDiagra().split("[,]");
					map.put("masterDiagraList", masterDiagraList);
				}
				if (StringUtils.isNotEmpty(ppp.getImpreDrawing())) {
					String impreDrawingList[] = ppp.getImpreDrawing().split("[,]");
					map.put("impreDrawingList", impreDrawingList);
				}
				if (StringUtils.isNotEmpty(ppp.getTemplateDrawing())) {
					String templateDrawingList[] = ppp.getTemplateDrawing().split("[,]");
					map.put("templateDrawingList", templateDrawingList);
				}
				if (StringUtils.isNotEmpty(ppp.getRealDiagra())) {
					String realDiagraList[] = ppp.getRealDiagra().split("[,]");
					map.put("realDiagraList", realDiagraList);
				}
				map.put("premisesPmo", resPPP.getEntity().get(0));
			}
			
		
		
		}
		return "/estate/projectPremises/save_edit_lc";
	}
	
	@RequestMapping(value = "save_edit")
	@MerchantResourcesConfig(resourcesCode="menu_0003_0001_0014")
	public String saveEdit(ModelMap map, Long id, HttpServletRequest request, HttpServletResponse servletResponse) {
		//产品类型
		map.put("projectTypes", ProjectTypeEnum.values());
		//交付情况
		map.put("deliveryStatusEnums", DeliveryStatusEnum.values());
		//销售情况
		map.put("salesStatusEnums", SalesStatusEnum.values());
		
		//物业类型
		map.put("tenementTypeEnums", TenementTypeEnum.values());
		// 装修标准
		map.put("renovationTypeEnums", RenovationTypeEnums.values());
		
		User user=ShiroUtil.getCurrentUser();
		DepartmentDto dto=new DepartmentDto();
		dto.setMerchantId(user.getMerchantId());
		ResponseList<Department> responseList=departmentServiceFacade.findByDto(dto);
		if(responseList.isSuccess() && null!=responseList.getEntity()){
			map.put("departments", responseList.getEntity());
		}else{
			map.put("departments", new ArrayList<Department>());
		}
		
		Response<ProjectPremises> response=projectPremisesServiceFacade.findById(id);
		if(response.isSuccess()&&response.getEntity()!=null){
			//项目信息
			Response<Project> resProject = projectServiceFacade.findById(response.getEntity().getProjectId());
			if(resProject.isSuccess() && resProject.getEntity() != null){
				map.put("project", resProject.getEntity());
			}
			
			//组团信息
			map.put("premises", response.getEntity());
			
			//组团详情
			ProjectPremisesInfoDto ppiDto = new ProjectPremisesInfoDto();
			ppiDto.setPremisesId(id);
			ResponseList<ProjectPremisesInfo> resPPI = projectPremisesInfoServiceFacade.findByDto(ppiDto);
			if(resPPI.isSuccess() && null != resPPI.getEntity() && resPPI.getEntity().size()>0){
				map.put("projectPremisesInfo", resPPI.getEntity().get(0));
			}
		}
		return "/estate/projectPremises/save_edit";
	}

	// 查看
	@RequestMapping(value = "detailLC")
	public String basicDetail(Long id, ModelMap map) {
		AjaxRes ar = getAjaxRes();
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "estate:projectPremises:view"))) {
		    ProjectPremises premises = projectPremisesServiceFacade.findById(id).getEntity();
		    map.put("projectId", premises.getProjectId());
		    map.put("id", id);
		    return "/estate/projectPremises/detailLC";
		}
		return Const.NO_AUTHORIZED_URL;
	}
	
	// 查看
	@RequestMapping(value = "detail")
	@MerchantResourcesConfig(resourcesCode="menu_0003_0001_0013")
	public String detail(Long id, ModelMap map, HttpServletRequest request, HttpServletResponse servletResponse) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "estate:projectPremises:view"))) {
			try {
				map.put("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
				
				Response<ProjectPremises> response = projectPremisesServiceFacade.findById(id);
				
				if (response.isSuccess()) {
					//项目PMO
					ProjectPremises projectPremises=response.getEntity();
					// 产品类型
					map.put("projectTypes", ProjectTypeEnum.values());
					// 交付情况
					map.put("deliveryStatusEnums", DeliveryStatusEnum.values());
					// 销售情况
					map.put("salesStatusEnums", SalesStatusEnum.values());
					// 物业类型
					map.put("tenementTypeEnums", TenementTypeEnum.values());

					Map<String, String> projectMap = new HashMap<String, String>();
					projectMap = projectServiceFacade.projectLevelName(id, "2");
					map.addAttribute("manageObject", projectMap.get("manageObject"));
					map.addAttribute("parentName", projectMap.get("parentName"));
					

					// 组团详情
					ProjectPremisesInfoDto ppiDto = new ProjectPremisesInfoDto();
					ppiDto.setPremisesId(id);
					ResponseList<ProjectPremisesInfo> resPPI = projectPremisesInfoServiceFacade.findByDto(ppiDto);
					if (resPPI.isSuccess() && null != resPPI.getEntity() && resPPI.getEntity().size() > 0) {
						map.put("projectPremisesInfo", resPPI.getEntity().get(0));
					}
					
					//车位配比=总户数:车位
					map.put("premises", projectPremises);
					// 组团PMO详情
				
					ProjectPremises projectPremisesObj = new ProjectPremises();
					projectPremisesObj.setId(id);
					ar.setSucceed(response.getEntity());
				} else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
				map.addAttribute("ar", ar);
				return "/estate/projectPremises/detail";
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return Const.NO_AUTHORIZED_URL;
	}
	
	public HashMap<String, Object> returnValue(LevelStaticSalesData salesData,Long premeseId){
		HashMap<String, Object> map = new HashMap<String, Object>();
		List<StaticSalesIndustData> array = new ArrayList<StaticSalesIndustData>();
		if(salesData.getStaticSalesDatas()!=null&&salesData.getStaticSalesDatas().size()>0){
			for (LevelStaticSalesDataChild child:salesData.getStaticSalesDatas()) {
				if(child.getPremisesId().compareTo(premeseId)==0){
					StaticSalesData staticSalesData = child.getData();
					map.put("staticSalesData", staticSalesData);
					if(staticSalesData.getIndust()!=null&&staticSalesData.getIndust().size()>0){
						List<StaticSalesIndustData> dataList = staticSalesData.getIndust();
						for (StaticSalesIndustData data:dataList) {
							if(data.getParentId()==null){ //大业态累计值
								array.add(data);
							}
						}
						map.put("salesIndustDataList", array);
					}
					return map;
				}
			}
		}
		return map;
	}
	
	
	
	public HashMap<String, Object> getDynamicData(LevelDynamiSalesData levelDynamiSalesData,String pmoPremisesId){
		HashMap<String, Object> map = new HashMap<String, Object>();
		if(levelDynamiSalesData.getDynamiSalesDatas()!=null&&levelDynamiSalesData.getDynamiSalesDatas().size()>0){
			for (LevelDynamiSalesData salesData:levelDynamiSalesData.getDynamiSalesDatas()) {
				if(StringUtils.isNotBlank(salesData.getProjectCode()) && StringUtils.isNotBlank(pmoPremisesId) && salesData.getProjectCode().equals(pmoPremisesId)){
					//分期动态数据
					DynamiSalesData dynamiSalesData = salesData.getData();
					List<DynamiSalesIndustData> salesList = dynamiSalesData.getIndust();
					for (DynamiSalesIndustData data:salesList) {
						BaseCodeValueDto codeValue = new BaseCodeValueDto();
						codeValue.setCodeValue(data.getIndustMark());
						User user = ShiroUtil.getCurrentUser();
						codeValue.setMerchantId(user.getMerchantId());
						ResponseList<BaseCodeValue> responseCode = baseCodeValueServiceFacade.findByDto(codeValue);
						if(responseCode.isSuccess()&&responseCode.getEntity()!=null&&responseCode.getEntity().size()>0){
							BaseCodeValue baseCode = responseCode.getEntity().get(0);
							data.setIndustMark(baseCode.getCodeName());
						}else{
							BaseCodeTypeDto codeType = new BaseCodeTypeDto();
							codeType.setMerchantId(user.getMerchantId());
							codeType.setTypeValue(data.getIndustMark());
							ResponseList<BaseCodeType>  responseType = baseCodeTypeServiceFacade.findByDto(codeType);
							if(responseType.isSuccess()&&responseType.getEntity()!=null&&responseType.getEntity().size()>0){
								BaseCodeType baseCodeType = responseType.getEntity().get(0);
								data.setIndustMark(baseCodeType.getTypeName());
							}
						}
						
					}
					map.put("dynamiSalesIndustData", salesList);
					map.put("dynamiSalesData", dynamiSalesData);
				}
			}
		}
		return map;
	}
	
	
	public List<ViewVersion> viewVersion(List<ProjectPremisesIndustData> industData){
		List<ViewVersion> array = new ArrayList<ViewVersion>();
		BigDecimal value2 = new BigDecimal("0");
		BigDecimal value4 = new BigDecimal("0");
		BigDecimal value6 = new BigDecimal("0");
		BigDecimal value8 = new BigDecimal("0");
		BigDecimal value10 = new BigDecimal("0");
		BigDecimal value12 = new BigDecimal("0");
		if(null!=industData){
			for (ProjectPremisesIndustData list:industData) {
				if(list.getIndustDataVersion()!=null){
					IndustDataVersion vesion = list.getIndustDataVersion();
					BigDecimal v2 = StringUtils.isEmpty(vesion.getValue2())?new BigDecimal("0"):new BigDecimal(vesion.getValue2());
					BigDecimal v2_s = list.getSalableAcreag()==null?new BigDecimal("0"):list.getSalableAcreag();
					v2_s = v2_s.multiply(new BigDecimal("10000"));
					//万平方米 转成平方米 , 目标销售均价 * 可售面积 + 自持货值

					BigDecimal targetValue = list.getTargetValue()==null?new BigDecimal(0):list.getTargetValue();
					value2=value2.add(v2.multiply(v2_s).add(targetValue));
					
					BigDecimal v4 = StringUtils.isEmpty(vesion.getValue4())?new BigDecimal("0"):new BigDecimal(vesion.getValue4());
					value4=value4.add(v4.multiply(v2_s).add(targetValue));
					
					BigDecimal v6 = StringUtils.isEmpty(vesion.getValue6())?new BigDecimal("0"):new BigDecimal(vesion.getValue6());
					value6=value6.add(v6.multiply(v2_s).add(targetValue));
					BigDecimal v8 = StringUtils.isEmpty(vesion.getValue8())?new BigDecimal("0"):new BigDecimal(vesion.getValue8());
					value8=value8.add(v8.multiply(v2_s).add(targetValue));
					BigDecimal v10 = StringUtils.isEmpty(vesion.getValue10())?new BigDecimal("0"):new BigDecimal(vesion.getValue10());
					value10=value10.add(v10.multiply(v2_s).add(targetValue));
					BigDecimal v12 = StringUtils.isEmpty(vesion.getValue12())?new BigDecimal("0"):new BigDecimal(vesion.getValue12());
					value12=value12.add(v12.multiply(v2_s).add(targetValue));

				}
			}
		}
		
		
		array.add(new ViewVersion("拓展版", value2));
		array.add(new ViewVersion("启动会版", value4));
		array.add(new ViewVersion("方案版", value6));
		array.add(new ViewVersion("施工图版", value8));
		array.add(new ViewVersion("结算版", value10));
		array.add(new ViewVersion("经营计划版", value12));
	
		return array;
	}
	
	// 新增返回实体对象
	@RequestMapping(value = "add", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes add(ProjectPremisesDto dto) {
		AjaxRes ar = getAjaxRes();

		/*
		 * 1.判断权限2.调用新增接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "estate:projectPremises:add"))) {
			try {
				User user = ShiroUtil.getCurrentUser();
				dto.setMerchantId(user.getMerchantId());
				dto.setCreateUserId(user.getId());
				dto.setDelFlag("0");
				dto.setUpdateUserId(user.getId());
				dto.setUpdateTime(new Date());
				Response<ProjectPremisesDto> response = projectPremisesServiceFacade.save(dto);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.SAVE_SUCCEED);
				} else {
					ar.setFailMsg(Const.SAVE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.SAVE_FAIL);
			}
		}
		return ar;
	}

	// 查看
	@RequestMapping(value = "view", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes view(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "estate:projectPremises:view"))) {
			try {
				Response<ProjectPremises> response = projectPremisesServiceFacade.findById(id);
				if (response.isSuccess()) {
					ar.setSucceed(response.getEntity());
				} else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return ar;
	}

	// 修改
	@RequestMapping(value = "edit", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes edit(ProjectPremisesVo ppVo, ProjectPremisesInfoVo ppiVo, ProjectPremisesPmoDto pppDto,
			SaleReturnPmoVo srpVo,HttpServletRequest request) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用修改接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "estate:projectPremises:edit"))) {
			try {
				/*String industData = ppVo.getIndustDataObj();
				PremisesIndustDatas premisesIndustDatas = JSON.parseObject(industData, PremisesIndustDatas.class);
				if (premisesIndustDatas != null) {// 保存业态数据
					projectPremisesIndustDataService.save(premisesIndustDatas, ppiVo.getPremisesId());
				}*/

				User user = ShiroUtil.getCurrentUser();
				ProjectPremisesDto ppDto = new ProjectPremisesDto();
				BeanUtils.copyProperties(ppVo, ppDto);
				ppDto.setUpdateUserId(user.getId());
				ppDto.setUpdateTime(Calendar.getInstance().getTime());
				/*SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");*/
				if (null != pppDto.getActualDueDate()) {
					ppVo.setDeliveryDate(pppDto.getActualDueDate());
				} else if (null != pppDto.getPlanneDueDate()) {
					ppVo.setDeliveryDate(pppDto.getPlanneDueDate());
				}
				Response<Integer> response = projectPremisesServiceFacade.updateByPrimaryKey(ppDto, true);
				if (response.isSuccess()) {
					Response<ProjectPremises> resPremises = projectPremisesServiceFacade.findById(ppiVo.getId());
					if (resPremises.isSuccess() && resPremises.getEntity() != null) {
						// 装在组团详情
						ProjectPremisesInfoDto ppiDto = new ProjectPremisesInfoDto();
						BeanUtils.copyProperties(ppiVo, ppiDto);

						ProjectPremises pp = resPremises.getEntity();
						if (StringUtils.isNotEmpty(ppiVo.getProjectInfoId())) {
							// 执行修改
							ppiDto.setId(Long.parseLong(ppiVo.getProjectInfoId()));
							ppiDto.setUpdateUserId(user.getId());
							ppiDto.setUpdateTime(Calendar.getInstance().getTime());
							projectPremisesInfoServiceFacade.updateByPrimaryKey(ppiDto, true);
						} else {
							// 执行新增
							ppiDto.setProjectCode(pp.getProjectCode());
							ppiDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
							ppiDto.setMerchantId(pp.getMerchantId());
							ppiDto.setUserCode(pp.getUserCode());
							ppiDto.setAccessCode(pp.getAccessCode());
							ppiDto.setCreateUserId(user.getId());
							ppiDto.setCreateTime(Calendar.getInstance().getTime());
							projectPremisesInfoServiceFacade.save(ppiDto);
						}

						// PMO组团信息
						// devlopCycle： 开发周期计算方式
						// 完善说明：时间区间为：开工日期-计划 --- 交付日期-计划
						// 注：当有实际开工时间，取开工日期-实际，原则上取分期最早的开工日期-最迟的交付日期
						String devlopCycle = "";
						if (null != ppVo.getPropertyYear()) {
							Date devlopCycleStart = null;
							String devlopCycleStartStr = "";
							Date devlopCycleEnd = null;
							String devlopCycleEndStr = "";
							if (null != pppDto.getPlanneStartOperatDate()) {
								devlopCycleStart = pppDto.getPlanneStartOperatDate();
							} else if (null != pppDto.getActualStartOperatDate()) {
								devlopCycleStart = pppDto.getActualStartOperatDate();
							}
							if (null != pppDto.getActualDueDate()) {
								devlopCycleEnd = pppDto.getActualDueDate();
							} else if (null != pppDto.getPlanneDueDate()) {
								devlopCycleEnd = pppDto.getPlanneDueDate();
							}
							SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");
							if (null != devlopCycleStart) {
								devlopCycleStartStr = sdf2.format(devlopCycleStart);
							}
							if (null != devlopCycleEnd) {
								devlopCycleEndStr = sdf2.format(devlopCycleEnd);
							}
							devlopCycle = devlopCycleStartStr + "-" + devlopCycleEndStr;
						}

						pppDto.setDevlopCycle(devlopCycle);
						pppDto.setProjectId(pp.getProjectId());
						pppDto.setProjectCode(pp.getProjectCode());
						pppDto.setPremisesId(pp.getId());
						pppDto.setPremisesCode(pp.getPremisesCode());
						if (StringUtils.isNotEmpty(pppDto.getPremisesPmoId())) {
							// 执行修改
							pppDto.setId(Long.parseLong(pppDto.getPremisesPmoId()));
							pppDto.setUpdateUserId(user.getId());
							pppDto.setUpdateTime(Calendar.getInstance().getTime());
							projectPremisesPmoServiceFacade.updateByPrimaryKey(pppDto, true);
						} else {
							// 执行新增
							pppDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
							pppDto.setCreateUserId(user.getId());
							pppDto.setCreateTime(Calendar.getInstance().getTime());
							projectPremisesPmoServiceFacade.save(pppDto);
						}
//						// 调用接口,通知商户信息变更
//						long merchantId = user.getMerchantId();
//						if (merchantId == 1) {
//							try{
//								levelStaticSalesDataService.updateProjectInfo(pp.getMerchantId(), pp.getProjectId());
//							}catch(Exception ex){
//								ex.printStackTrace();
//							}
//						}
						//销售指标信息
						String srpSale = srpVo.getSrpSale();
						JSONArray srpSaleArray = JSONArray.parseArray(srpSale);
						if(null != srpSaleArray){
							for(int ii=0; ii<srpSaleArray.size(); ii++){
								JSONObject srpSaleObj = srpSaleArray.getJSONObject(ii);
								String id = srpSaleObj.getString("saleInfoId");
								String saleDiffReason = srpSaleObj.getString("saleDiffReason");
								String saleActual = srpSaleObj.getString("saleActual");
								String saleDiff = srpSaleObj.getString("saleDiff");
								if(StringUtils.isNotEmpty(id)){
									SaleReturnPmoDto srpDto = new SaleReturnPmoDto();
									srpDto.setId(Long.parseLong(id));
									srpDto.setSaleDiffReason(saleDiffReason);
									srpDto.setSaleActual(saleActual);
									srpDto.setSaleDiff(saleDiff);
									saleReturnPmoServiceFacade.updateByPrimaryKey(srpDto, true);
									
								}
							}
						}
						//回款指标信息
						String srpReturn = srpVo.getSrpReturn();
						JSONArray srpReturnArray = JSONArray.parseArray(srpReturn);
						if(null != srpReturnArray){
							for(int ii=0; ii<srpReturnArray.size(); ii++){
								JSONObject srpReturnObj = srpReturnArray.getJSONObject(ii);
								String id = srpReturnObj.getString("returnInfoId");
								String saleDiffReason = srpReturnObj.getString("saleDiffReason");
								String saleActual = srpReturnObj.getString("saleActual");
								String saleDiff = srpReturnObj.getString("saleDiff");
								if(StringUtils.isNotEmpty(id)){
									SaleReturnPmoDto srpDto = new SaleReturnPmoDto();
									srpDto.setId(Long.parseLong(id));
									srpDto.setSaleDiffReason(saleDiffReason);
									srpDto.setSaleActual(saleActual);
									srpDto.setSaleDiff(saleDiff);
									saleReturnPmoServiceFacade.updateByPrimaryKey(srpDto, true);
								}
							}
						}
						//动态货值偏差原因
						String srpDynamic = srpVo.getSrpDynamic();
						JSONArray srpDynamicArray = JSONArray.parseArray(srpDynamic);
						if(null != srpDynamicArray){
							for(int ii=0; ii<srpDynamicArray.size(); ii++){
								JSONObject srpDynamicObj = srpDynamicArray.getJSONObject(ii);
								String id = srpDynamicObj.getString("dynamicInfoId");
								String saleYear = srpDynamicObj.getString("saleYear");
								String saleMonth = srpDynamicObj.getString("saleMonth");
								String salePlan = srpDynamicObj.getString("salePlan");
								String saleActual = srpDynamicObj.getString("saleActual");
								String saleDiff = srpDynamicObj.getString("saleDiff");
								String saleDiffReason = srpDynamicObj.getString("saleDiffReason");
								if(StringUtils.isNotEmpty(id)){
									SaleReturnPmoDto srpDto = new SaleReturnPmoDto();
									srpDto.setId(Long.parseLong(id));
									srpDto.setSalePlan(salePlan);
									srpDto.setSaleActual(saleActual);
									srpDto.setSaleDiff(saleDiff);
									srpDto.setSaleDiffReason(saleDiffReason);
									saleReturnPmoServiceFacade.updateByPrimaryKey(srpDto, true);
								}else{
									SaleReturnPmoDto srpDto = new SaleReturnPmoDto();
									srpDto.setSaleReturn(SaleReturnEnum.DYNAMIC.getNo());
									srpDto.setObjectType(ObjectTypeEnum.PREMISES.getNo());
									srpDto.setObjectId(pp.getId());
									srpDto.setSaleYear(saleYear);
									srpDto.setSaleMonth(saleMonth);
									srpDto.setSalePlan(salePlan);
									srpDto.setSaleActual(saleActual);
									srpDto.setSaleDiff(saleDiff);
									srpDto.setSaleDiffReason(saleDiffReason);
									srpDto.setCreateUserId(user.getId());
									srpDto.setDelFlag(DelFlagEnum.UNDEL.getNo());
									saleReturnPmoServiceFacade.save(srpDto);
								}
							}
						}
					}
					ar.setSucceedMsg(Const.UPDATE_SUCCEED);
				} else {
					ar.setFailMsg(Const.UPDATE_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.UPDATE_FAIL);
			}
		}
		return ar;
	}

	// 删除
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes delete(Long id) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用查看接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "estate:projectPremises:delete"))) {
			try {
				Response<Integer> response = projectPremisesServiceFacade.deleteByPrimaryKey(id);
				if (response.isSuccess()) {
					ar.setSucceedMsg(Const.DEL_SUCCEED);
				} else {
					ar.setFailMsg(Const.DEL_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DEL_FAIL);
			}
		}
		return ar;
	}

	// 分页查询
	@RequestMapping(value = "list", method = RequestMethod.POST)
	@ResponseBody
	public AjaxRes list(ProjectPremisesDto dto, Integer pageSize, Integer pageNum) {
		AjaxRes ar = getAjaxRes();
		/*
		 * 1.判断权限2.调用分页查询接口3.返回信息
		 */
		if (ar.setNoAuth(doSecurityIntercept(Const.RESOURCES_TYPE_BUTTON, "estate:projectPremises:list"))) {
			try {
				Page<ProjectPremises> response = projectPremisesServiceFacade.findPageByDto(dto,
						PageUtil.begin(pageNum, pageSize), pageSize);
				if (response.getSuccess()) {
					if (null == response.getRows())
						response.setRows(new ArrayList<ProjectPremises>());
					response.setPageNumber(pageNum);
					ar.setSucceed(response);
				} else {
					ar.setFailMsg(Const.DATA_FAIL);
				}
			} catch (Exception e) {
				logger.error(e.toString(), e);
				ar.setFailMsg(Const.DATA_FAIL);
			}
		}
		return ar;
	}

	@RequestMapping(value = "findPremisesList")
	public @ResponseBody
	RootClass findPremisesList(ProjectPremisesDto dto) {
		User user = ShiroUtil.getCurrentUser();
		dto.setDelFlag("0");
		dto.setMerchantId(user.getMerchantId());
		ResponseList<ProjectPremises> premisesList = projectPremisesServiceFacade.findByDto(dto);
		RootClass root = new RootClass();
		root.setRoot(premisesList.getEntity());
		return root;
	}
	/**
	 * 
	 * toProjectInfo:(组团基本信息). <br/>
	 *
	 * @author Administrator
	 * @param map
	 * @param request
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping(value = "toProjectInfo")
	public String toProjectInfo(ModelMap map, HttpServletRequest request,Long id) {
	    request.setAttribute("permitBtn", getPermitBtn(Const.RESOURCES_TYPE_FUNCTION));
	    Response<ProjectPremises> projectPremises = projectPremisesServiceFacade.findById(id);
	    request.setAttribute("premises", projectPremises.getEntity());
	    Response<Project> projectInfo = projectServiceFacade.findById(projectPremises.getEntity().getProjectId());
	    request.setAttribute("project", projectInfo.getEntity());
	    request.setAttribute("deliveryStatusEnums", DeliveryStatusEnum.values());
	    request.setAttribute("salesStatusEnums", SalesStatusEnum.values());
	    request.setAttribute("projectTypes", ProjectTypeEnum.values());
	    //分期PMO信息
	    ProjectPremisesPmoDto premisesPmoDto = new ProjectPremisesPmoDto();
	    premisesPmoDto.setPremisesId(id);
	    ResponseList<ProjectPremisesPmo> premisesPmoList = projectPremisesPmoServiceFacade.findByDto(premisesPmoDto);
	    if(premisesPmoList.isSuccess()&&premisesPmoList.getEntity()!=null){
		ProjectPremisesPmo projectPremisesPmo = premisesPmoList.getEntity().get(0);
		request.setAttribute("logoList", getImagesList(projectPremisesPmo.getLogoUrl()));
		request.setAttribute("traffiDiagraList", getImagesList(projectPremisesPmo.getTraffiDiagra()));
		request.setAttribute("aroundSupporDiagraList", getImagesList(projectPremisesPmo.getAroundSupporDiagra()));
		request.setAttribute("masterDiagraList", getImagesList(projectPremisesPmo.getMasterDiagra()));
		request.setAttribute("impreDrawingList", getImagesList(projectPremisesPmo.getImpreDrawing()));
		request.setAttribute("templateDrawingList", getImagesList(projectPremisesPmo.getTemplateDrawing()));
		request.setAttribute("realDiagraList", getImagesList(projectPremisesPmo.getRealDiagra()));
		request.setAttribute("premisesPmo", projectPremisesPmo);
	    }
	    
	    //分期基本信息
	    ProjectPremisesInfoDto premisesInfoDto = new ProjectPremisesInfoDto();
	    premisesInfoDto.setPremisesId(id);
	    ResponseList<ProjectPremisesInfo> premisesInfoList = projectPremisesInfoServiceFacade.findByDto(premisesInfoDto);
	    if (premisesInfoList.isSuccess() && null != premisesInfoList.getEntity() && premisesInfoList.getEntity().size() > 0) {
		request.setAttribute("projectPremisesInfo", premisesInfoList.getEntity().get(0));
	    }
	    
	    //项目信息
	   
	    return "/estate/projectPremises/projectInfo";
	}
	
	public String[] getImagesList(String str){
	     if(!StringUtil.isEmpty(str)){
		 return str.split(",");
	     }
	     return null;
	}
	/**
	 * 
	 * toSaleView:(组团分期信息). <br/>

	 *
	 * @author Administrator
	 * @param map
	 * @param request
	 * @return
	 * @since JDK 1.6
	 */
	@RequestMapping(value = "toSaleView")
	public String toSaleView(ModelMap map, HttpServletRequest request) {
		return "/estate/projectPremises/saleView";
	}
	
	
}
